/**
 * main activity.
 * @author William
 * 2012-2-26
 */
package com.ytu.cloudbackup.face;

import java.io.IOException;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.api.client.googleapis.auth.clientlogin.ClientLogin;
import com.google.api.client.googleapis.auth.clientlogin.ClientLogin.ErrorInfo;
import com.google.api.client.http.HttpResponseException;

public class CloudBackupActivity extends Activity {

	// 控件声明
	private Button btn_sub;
	private Button btn_cancel;
	private EditText user;
	private EditText psd;

	// 变量声明
	private static final String ACCOUNT_TYPE = "com.google";
	private static final int DLG_ACCOUNTS = 1;

	private static final String PICASA_ACCOUNT_TYPE = "lh2";
	private static final String DOCS_ACCOUNT_TYPE = "writely";

	public static final String PICASA_TOKEN = "ptoken";
	public static final String DOCS_TOKEN = "dtoken";

	public static SharedPreferences pref;
	private String Dauth = null;
	private String Pauth = null;

	private void init() {
		btn_sub = (Button) findViewById(R.id.submit);
		btn_cancel = (Button) findViewById(R.id.cancel);
		user = (EditText) findViewById(R.id.user);
		psd = (EditText) findViewById(R.id.psd);

		btn_sub.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				storeToken(PICASA_TOKEN, getToken(PICASA_ACCOUNT_TYPE));
				storeToken(DOCS_TOKEN, getToken(DOCS_ACCOUNT_TYPE));
				loginned();
			}

		});

		btn_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}

		});
	}

	private String getToken(String type) {
		ClientLogin clientLogin;
		ClientLogin.Response response;
		clientLogin = new ClientLogin();
		response = new ClientLogin.Response();
		clientLogin.accountType = "GOOGLE";
		clientLogin.applicationName = "CloudBackup";
		clientLogin.authTokenType = type;

		clientLogin.username = "lp88513@gmail.com";// user.getText().toString().trim();
		clientLogin.password = "loveyoubbl*"; //psd.getText().toString().trim();

		try {
			response = clientLogin.authenticate();
			
		} catch (HttpResponseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return response.auth;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		init();
	}

	/* 账户选择对话框的创建 */
	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		switch (id) {
		case DLG_ACCOUNTS:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			final Account[] accounts = getBindAccounts(ACCOUNT_TYPE);
			int len = accounts.length;
			String[] names = new String[len];
			for (int i = 0; i < len; i++) {
				names[i] = accounts[i].name;
			}
			builder.setTitle("Please Select a Account")
					.setIcon(R.drawable.accounts)
					.setItems(names, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 获取选择的Token存入XML
							// Toast.makeText(CloudBackupActivity.this,accounts[which].name,Toast.LENGTH_SHORT).show();
							try {
								if (storeToken(
										CloudBackupActivity.PICASA_TOKEN,
										getPToken(accounts[which]))) {
									Toast.makeText(CloudBackupActivity.this,
											"Login Picasa success!",
											Toast.LENGTH_SHORT).show();
								} else {
									Toast.makeText(CloudBackupActivity.this,
											"Login Picasa failed!",
											Toast.LENGTH_SHORT).show();
								}

								if (storeToken(CloudBackupActivity.DOCS_TOKEN,
										getDToken(accounts[which]))) {
									Toast.makeText(CloudBackupActivity.this,
											"Login Docs success!",
											Toast.LENGTH_SHORT).show();
								} else {
									Toast.makeText(CloudBackupActivity.this,
											"Login Docs failed!",
											Toast.LENGTH_SHORT).show();
								}

							} catch (OperationCanceledException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (AuthenticatorException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						}
					});
			return builder.create();
		default:
			return null;
		}
	}

	protected String getDToken(final Account account)
			throws OperationCanceledException, AuthenticatorException {
		final AccountManager managerD = AccountManager.get(this);

		/* 新开个线程获取auth */
		try {
			Dauth = (String) managerD.blockingGetAuthToken(account,
					DOCS_ACCOUNT_TYPE, true);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Dauth;
	}

	/* 获取系统绑定账户 */
	public Account[] getBindAccounts(String type) {

		AccountManager manager = AccountManager.get(this);
		Account[] accounts = manager.getAccountsByType(type);
		return accounts;

	}

	protected String getPToken(final Account account)
			throws OperationCanceledException, AuthenticatorException {
		final AccountManager managerP = AccountManager.get(this);
		final String name = account.name;
		try {
			Pauth = managerP
					.getAuthToken(account, PICASA_ACCOUNT_TYPE, null,
							CloudBackupActivity.this, null, null).getResult()
					.getString(AccountManager.KEY_AUTHTOKEN).toString();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Pauth;
	}

	/* 存储获取到得Token */
	protected boolean storeToken(String keys, String auth) {
		pref = getSharedPreferences("AUTHMSG", MODE_PRIVATE);
		if (auth != null) {
			pref.edit().putString(keys, auth).commit();
			return true;
		}
		return false;
	}

	public void loginned() {
		Intent i = new Intent(this, FileExplorer.class);
		startActivity(i);

	}
}